package com.sencorsta.ids.core.tcp.websocket;

import com.sencorsta.ids.core.tcp.opensocket.OpenDecoder;
import com.sencorsta.ids.core.tcp.opensocket.OpenEncoder;
import com.sencorsta.ids.core.tcp.opensocket.OpenServerBootstrap;
import com.sencorsta.ids.core.tcp.opensocket.OpenUser;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

import java.util.List;

public class SocketChooseHandle extends ByteToMessageDecoder {
    /**
     * 默认暗号长度为23
     */
    private static final int MAX_LENGTH = 23;
    /**
     * WebSocket握手的协议前缀
     */
    private static final String WEBSOCKET_PREFIX = "GET /";


    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
        String protocol = getBufStart(in);

        if (protocol.startsWith(WEBSOCKET_PREFIX)) {
            new PipelineAdd().websocketAdd(ctx);
            ctx.pipeline().remove(OpenDecoder.class);
            ctx.pipeline().remove(OpenEncoder.class);
            //ctx.pipeline().remove(BytebufToByteHandle.class);
        }
        OpenUser user = new OpenUser();
        user.channel = ctx.channel();
        user.channel.attr(OpenServerBootstrap.getInstance().KEY_OPENUSER).set(user);
        in.resetReaderIndex();
        ctx.pipeline().remove(this.getClass());

    }


    private String getBufStart(ByteBuf in) {
        int length = in.readableBytes();
        if (length > MAX_LENGTH) {
            length = MAX_LENGTH;
        }

        // 标记读位置
        in.markReaderIndex();
        byte[] content = new byte[length];
        in.readBytes(content);
        return new String(content);
    }
}
